#!/usr/bin/python
# -*- coding: utf-8 -*-

# THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: 
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),  
# to deal in the Software without restriction, including without limitation  
# the rights to use, copy, modify, merge, publish, distribute, sublicense,  
# and/or sell copies of the Software, and to permit persons to whom the  
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in 
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
# DEALINGS IN THE SOFTWARE.

# visuals.py
# written by: 
#     Jan Jokela <jan@devion.org>

import os, sys
from PIL import Image

def reflex(img, intensity=100.0):
    # reflex is a slow process, so we use a simple cache mechanism that stores
    # the reflex images in a hidden dir
    cache_path = os.path.join(os.path.expanduser('~'), '.mediaplex', 'cache')
    cached_img = os.path.join(os.path.expanduser('~'), '.mediaplex', 'cache', os.path.split(img)[1] + '.reflex' + str(intensity))
    if os.path.exists(cached_img): return cached_img
    else:
        # Lets load a tmp image
        tmp_img = Image.open(img)
        tmp_img.load()
        size = tmp_img.size
        tmp_img.mode = "RGBA"
        # We need another one because we do
        aux_img = Image.open(img)
        aux_img.load()
        aux_img.mode = "RGBA"
        
        ####
        for x in xrange(size[0]):
            for y in xrange(size[1]):
                spy = tmp_img.getpixel((x, y))
                if len(spy) < 4:
                    spy = (spy[0], spy[1], spy[2], 255)
                aux_img.putpixel((x, size[1] - y - 1), spy)
        pos = intensity * size[1] / 100.0
        for x in xrange(size[0]):
            for y in xrange(size[1]):
                spy = aux_img.getpixel((x, y))
                if len(spy) < 4:
                    spy = (spy[0], spy[1], spy[2], 255)
                rel_intensity = (pos - y) * 1.0 / pos
                if y <= pos: alpha = spy[3] * rel_intensity
                else: alpha = 0.0
                tmp_img.putpixel((x, y), (spy[0],spy[1],spy[2],alpha)) 

        tmp_img.save(cached_img, "PNG")
        del tmp_img, aux_img
        return cached_img
        